package com.glink.manage.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.LogUtil;
import com.glink.common.vo.ResponseResult;
import com.glink.manage.dto.person.*;
import com.glink.manage.service.*;
import com.glink.manage.vo.org.OrgPersonInfoVO;
import com.glink.manage.vo.person.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author  qiushaoshan
 * @since  2025-01-13
 */
@RestController
@RequestMapping("/API/Manage/personManage")
@Api(tags = "人员管理")
@Slf4j
public class PersonManageController extends AbstractBaseController {

    @Autowired
    private PersonManageService personManageService;

    @Autowired
    private PersonViolationRegulationsRecordService personViolationRegulationsRecordService;

    @Autowired
    private PersonTrainingRecordService personTrainingRecordService;

    @Autowired
    private PersonAccessRelaService personAccessRelaService;
    
    @Autowired
    private BarrierGateService barrierGateService;
    
    @ApiOperation(value = "01.新增人员信息")
    @PostMapping(value = "/insert", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> insertPerson(@Validated @RequestBody PersonManageSaveDTO dto) throws GeneralSimpleException {
        log.info("01.新增人员信息：{}", LogUtil.encode(dto));
        String personId = personManageService.insertPerson(dto);
        boolean status = true;
        if(StringUtils.isNotBlank(personId)){
            // 部门人员直接下发准入，否则不下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjIdAndDepartment(personId));
        }else{
            status = false;
        }
        log.info("01.新增人员信息：success");
        return this.response(status);
    }

    @ApiOperation(value = "02.更新人员信息")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> updatePerson(@Validated @RequestBody PersonManageUpdateDTO dto) throws GeneralSimpleException {
        log.info("02.更新人员信息：{}", LogUtil.encode(dto));
        String personId = personManageService.updatePerson(dto);
        boolean status = true;
        if(StringUtils.isNotBlank(personId)){
            // 部门人员直接下发准入，否则不下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjIdAndDepartment(personId));
        }else{
            status = false;
        }
        log.info("02.更新人员信息：success");
        return this.response(status);
    }

    @ApiOperation(value = "03.根据ID查询人员信息")
    @PostMapping(value = "/findById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<PersonSimpleInfoVO> findById(@Validated @RequestBody PersonManageIdDTO dto) throws GeneralSimpleException {
        log.info("03.根据ID查询人员信息：{}", LogUtil.encode(dto));
        PersonSimpleInfoVO simpleInfoVO = personManageService.findById(dto);
        log.info("03.根据ID查询人员信息：success");
        return this.response(simpleInfoVO);
    }

    @ApiOperation(value = "04.分页查询违章记录")
    @PostMapping(value = "/pageByViolationRegulationsRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<IPage<PersonViolationRegulationsRecordVO>> pageByViolationRegulationsRecord(@Validated @RequestBody PersonViolationRegulationsRecordPageDTO dto) throws GeneralSimpleException {
        log.info("03.根据ID查询人员信息：{}", LogUtil.encode(dto));
        IPage<PersonViolationRegulationsRecordVO> regulationsRecordVOIPage = personViolationRegulationsRecordService.pageByViolationRegulationsRecord(dto);
        log.info("03.根据ID查询人员信息：success");
        return this.response(regulationsRecordVOIPage);
    }

    @ApiOperation(value = "05.分页查询培训记录")
    @PostMapping(value = "/pageByTrainingRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<IPage<PersonTrainingRecordVO>> pageByTrainingRecord(@Validated @RequestBody PersonTrainingRecordPageDTO dto) throws GeneralSimpleException {
        log.info("05.分页查询培训记录：{}", LogUtil.encode(dto));
        IPage<PersonTrainingRecordVO> regulationsRecordVOIPage = personTrainingRecordService.pageByTrainingRecord(dto);
        log.info("05.分页查询培训记录：success");
        return this.response(regulationsRecordVOIPage);
    }

    @ApiOperation(value = "06.分页查询人员信息")
    @PostMapping(value = "/pageByPersonInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
        @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    public ResponseResult<IPage<PersonPageVO>> pageByPersonInfo(@Validated @RequestBody PersonManagePageDTO dto) throws GeneralSimpleException {
        log.info("06.分页查询人员信息：{}", LogUtil.encode(dto));
        IPage<PersonPageVO> regulationsRecordVOIPage = personManageService.pageByPersonInfo(dto);
        log.info("06.分页查询人员信息：success");
        return this.response(regulationsRecordVOIPage);
    }

    @ApiOperation(value = "07.删除人员信息")
    @PostMapping(value = "/delByObjId", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> delByObjId(@Validated @RequestBody PersonManageIdDTO dto) throws GeneralSimpleException {
        log.info("07.删除人员信息：{}", LogUtil.encode(dto));
        Boolean status = personManageService.delByObjId(dto);
        if(status){
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonDataDelete(dto.getObjId()));
        }
        
        log.info("07.删除人员信息：success");
        return this.response(status);
    }

    @ApiOperation(value = "09.加入/取消黑名单")
    @PostMapping(value = "/addBlacklist", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> addBlacklist(@Validated @RequestBody PersonManageBlacklistIdDTO dto) throws GeneralSimpleException {
        log.info("09.加入/取消黑名单：{}", LogUtil.encode(dto));
        Boolean status = personManageService.addBlacklist(dto);
        if(status){
            // 部门人员直接下发准入，否则不下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjId(dto.getObjId()));
        }
        log.info("09.加入/取消黑名单：success");
        return this.response(status);
    }

    @ApiOperation(value = "10.新增违章记录")
    @PostMapping(value = "/saveViolationRegulationsRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> saveViolationRegulationsRecord(@Validated @RequestBody PersonViolationRegulationsRecordSaveDTO dto) throws GeneralSimpleException {
        log.info("10.新增违章记录：{}", LogUtil.encode(dto));
        boolean status = personViolationRegulationsRecordService.saveViolationRegulationsRecord(dto);
        log.info("10.新增违章记录：success");
        return this.response(status);
    }

    @ApiOperation(value = "11.新增培训记录")
    @PostMapping(value = "/saveTrainingRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> saveTrainingRecord(@Validated @RequestBody PersonTrainingRecordSaveDTO dto) throws GeneralSimpleException {
        log.info("11.新增培训记录：{}", LogUtil.encode(dto));
        boolean status = personTrainingRecordService.saveTrainingRecord(dto);
        log.info("11.新增培训记录：success");
        return this.response(status);
    }

    @ApiOperation(value = "12.删除违章记录")
    @PostMapping(value = "/delViolationRegulationsRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> delViolationRegulationsRecord(@Validated @RequestBody PersonViolationRegulationsRecordIdDTO dto) throws GeneralSimpleException {
        log.info("12.删除违章记录：{}", LogUtil.encode(dto));
        boolean status = personViolationRegulationsRecordService.delViolationRegulationsRecord(dto);
        log.info("12.删除违章记录：success");
        return this.response(status);
    }

    @ApiOperation(value = "13.删除培训记录")
    @PostMapping(value = "/delTrainingRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> delTrainingRecord(@Validated @RequestBody PersonTrainingRecordIdDTO dto) throws GeneralSimpleException {
        log.info("13.删除培训记录：{}", LogUtil.encode(dto));
        boolean status = personTrainingRecordService.delTrainingRecord(dto);
        log.info("13.删除培训记录：success");
        return this.response(status);
    }

    @ApiOperation(value = "14.分页查询人员信息-黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
            @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    @PostMapping(value = "/pageByPersonInfoBlacklist", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<IPage<PersonPageVO>> pageByPersonInfoBlacklist(@Validated @RequestBody PersonManagePageDTO dto) throws GeneralSimpleException {
        log.info("14.分页查询人员信息-黑名单：{}", LogUtil.encode(dto));
        IPage<PersonPageVO> regulationsRecordVOIPage = personManageService.pageByPersonInfoBlacklist(dto);
        log.info("14.分页查询人员信息-黑名单：success");
        return this.response(regulationsRecordVOIPage);
    }

    @ApiOperation(value = "15.查询人员信息-身份证号")
    @PostMapping(value = "/findByCard", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<PersonSimpleInfoCardVO> findByCard(@Validated @RequestBody PersonManageCardDTO dto) throws GeneralSimpleException {
        log.info("14.分页查询人员信息-黑名单：{}", LogUtil.encode(dto));
        PersonSimpleInfoCardVO simpleInfoCardVO = personManageService.findByCard(dto);
        log.info("14.分页查询人员信息-黑名单：success");
        return this.response(simpleInfoCardVO);
    }

    @ApiOperation(value = "16.黑名单--解除黑名单")
    @PostMapping(value = "/liftBlacklist", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> liftBlacklist(@Validated @RequestBody PersonManageIdDTO dto) throws GeneralSimpleException {
        log.info("16.黑名单--解除黑名单：{}", LogUtil.encode(dto));
        Boolean status = personManageService.liftBlacklist(dto);
        if(status){
            // 部门人员直接下发准入，否则不下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjId(dto.getObjId()));
        }
        log.info("16.黑名单--解除黑名单：success");
        return this.response(status);
    }

    @ApiOperation(value = "17.新增人员账号")
    @PostMapping(value = "/insertAccount", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> insertAccount(@Validated @RequestBody PersonAccountSaveDTO dto) throws GeneralSimpleException {
        log.info("17.新增人员账号：{}", LogUtil.encode(dto));
        boolean status = personManageService.insertAccount(dto);
        log.info("17.新增人员账号：success");
        return this.response(status);
    }

    @ApiOperation(value = "18.分页查询证件照-人员和车辆")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
            @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    @PostMapping(value = "/pageCertByPersonAndCar", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<IPage<CertificatePageVO>> pageCertByPersonAndCar(@Validated @RequestBody CertificatePageDTO dto) throws GeneralSimpleException {
        log.info("18.分页查询证件照-人员和车辆：{}", LogUtil.encode(dto));
        IPage<CertificatePageVO> certPageVOIPage = personManageService.pageCertByPersonAndCar(dto);
        log.info("18.分页查询证件照-人员和车辆：success");
        return this.response(certPageVOIPage);
    }

    @ApiOperation(value = "19.分页查询准入列表")
    @PostMapping(value = "/pageByAccess", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<IPage<PersonAccessPageVO>> pageByAccess(@Validated @RequestBody PersonAccessPageDTO dto) throws GeneralSimpleException {
        log.info("19.分页查询准入列表：{}", LogUtil.encode(dto));
        IPage<PersonAccessPageVO> regulationsRecordVOIPage = personAccessRelaService.pageByAccess(dto);
        log.info("19.分页查询准入列表：success");
        return this.response(regulationsRecordVOIPage);
    }
    
    @ApiOperation(value = "20.删除准入工程")
    @PostMapping(value = "/delAccessWork", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> delAccessWork(@Validated @RequestBody PersonAccessIdDTO dto) throws GeneralSimpleException {
        log.info("20.删除准入工程：{}", LogUtil.encode(dto));
        Boolean status = personAccessRelaService.delAccessWork(dto);
        if(status){
            // 删除人员准入，并重新核对人员信息并下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonDataDelete(dto.getPersonObjId()));
        }
        log.info("20.删除准入工程：success");
        return this.response(status);
    }

    @ApiOperation(value = "21.修改准入工程的准入周期")
    @PostMapping(value = "/updateAccessCycle", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Boolean> updateAccessCycle(@Validated @RequestBody PersonAccessCycleSaveDTO dto) throws GeneralSimpleException {
        log.info("21.修改准入工程的准入周期：{}", LogUtil.encode(dto));
        Boolean status = personAccessRelaService.updateAccessCycle(dto);
        
        if(status){
            // 校验人员是否在准入周期，是否需要重新下发
            CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjId(dto.getPersonObjId()));
        }
        
        log.info("21.修改准入工程的准入周期：success");
        return this.response(status);
    }

    @ApiOperation(value = "22.查询人员树形列表-带单位")
    @PostMapping(value = "/treeByPerson", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<List<OrgPersonInfoVO>> treeByPerson(@Validated @RequestBody PersonManageTreeDTO dto) throws GeneralSimpleException {
        log.info("22.查询人员树形列表-带单位：{}", LogUtil.encode(dto));
        List<OrgPersonInfoVO> status = personManageService.treeByPerson(dto);
        log.info("22.查询人员树形列表-带单位：success");
        return this.response(status);
    }

    @ApiOperation(value = "23.查询人员信息-待违章姓名模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
            @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    @PostMapping(value = "/findByName", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<List<PersonCardInfoVO>> findByName(@Validated @RequestBody PersonManageNameDTO dto) throws GeneralSimpleException {
        log.info("23.查询人员信息-待违章姓名模糊查询：{}", LogUtil.encode(dto));
        List<PersonCardInfoVO> cardInfoVOList = personManageService.findByName(dto);
        log.info("23.查询人员信息-待违章姓名模糊查询：success");
        return this.response(cardInfoVOList);
    }

    @ApiOperation(value = "24.导入人员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
            @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    @PostMapping(value = "/import", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<List<PersonExpVO>> importPersonInfo(@Validated MultipartFile file) throws GeneralSimpleException {
        log.info("24.导入人员信息");
        List<PersonExpVO> expVOList = personManageService.importPersonInfo(file);
        log.info("24.导入人员信息：success");
        return this.response(expVOList);
    }

    @ApiOperation(value = "25.导入人员头像")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "orgId", value = "当前登录用户的orgId", dataType = "string", required = true),
            @ApiImplicitParam(paramType = "header", name = "userId", value = "当前登录用户的userId", dataType = "string", required = true)})
    @PostMapping(value = "/importProfilePicture", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<List<PersonExpPictureVO>> importProfilePicture(@Validated MultipartFile file) throws GeneralSimpleException {
        log.info("25.导入人员头像");
        List<PersonExpPictureVO> expVOList = personManageService.importProfilePicture(file);
        log.info("25.导入人员头像：success");
        return this.response(expVOList);
    }
}
